package com.srpingde.hhh.application;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.DisplayMetrics;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class HhhApp extends Application {
	public static HhhApp weiQuApp;
	SharedPreferences preferences;
	DisplayMetrics dm = new DisplayMetrics();
	String USER_NAME = "user_name";
	String UID = "uid";
	String ID = "id";
	String PHONENUM = "phonenum";
	String ADDRESS = "address";
	String ISCHECK = "ischeck";
	String NAME = "name";
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		weiQuApp = this;
		initImageLoader();
		// 请求图片初始化
		ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(getApplicationContext()));
		dm = getResources().getDisplayMetrics();
		preferences = getApplicationContext().getSharedPreferences("weiqu", 0);
	}

	public static HhhApp getInstance() {
		return weiQuApp;
	}
	public boolean isConnect() {
	    try { 
	        ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext() 
	                .getSystemService(Context.CONNECTIVITY_SERVICE); 
	        if (connectivity != null) { 
	            NetworkInfo info = connectivity.getActiveNetworkInfo(); 
	            if (info != null&& info.isConnected()) { 
	                if (info.getState() == NetworkInfo.State.CONNECTED) { 
	                    return true; 
	                } 
	            } 
	        } 
	    } catch (Exception e) { 
	    	e.printStackTrace();
	    }
        return false; 
    }
	public void setDB(String key, Object value, SharedPreferences.Editor editor) {
		if (value instanceof String) {
			editor.putString(key, (String) value);
		} else if (value instanceof Boolean) {
			editor.putBoolean(key, (Boolean) value);
		} else if (value instanceof Integer) {
			editor.putInt(key, (Integer) value);
		}
	}
	//保存是否保存密码
	public boolean setLogin(boolean isCheck){
		SharedPreferences.Editor editor = preferences.edit();
		setDB(ISCHECK, isCheck, editor);
		return editor.commit();
	}
	public boolean getLogin(){
		return preferences.getBoolean(ISCHECK, false);
	}
	// 保存用户的uid
	public boolean setUid(String uid) {
		SharedPreferences.Editor editor = preferences.edit();
		setDB(UID, uid, editor);
		return editor.commit();
	}
	public void clear(){
		SharedPreferences.Editor editor = preferences.edit();
		editor.clear();
		editor.commit();
	}
	// 获取用户的UID
	public String getId() {
		return preferences.getString(ID, "");
	}
	// 保存用户的uid
	public boolean setId(String id) {
		SharedPreferences.Editor editor = preferences.edit();
		setDB(ID, id, editor);
		return editor.commit();
	}
	// 获取用户的UID
	public String getUid() {
		return preferences.getString(UID, "");
	}
	// 保存用户的uid
	public boolean setUname(String uname) {
		SharedPreferences.Editor editor = preferences.edit();
		setDB(USER_NAME, uname, editor);
		return editor.commit();
	}

	// 获取用户的UID
	public String getUname() {
		return preferences.getString(USER_NAME, "");
	}
	// 保存用户的收货的手机号
	public boolean setPhone(String phone) {
		SharedPreferences.Editor editor = preferences.edit();
		setDB(PHONENUM, phone, editor);
		return editor.commit();
	}

	// 获取用户的收货的手机号
	public String getPhone() {
		return preferences.getString(PHONENUM, "");
	}
	// 保存用户的地址
	public boolean setAddress(String phone) {
		SharedPreferences.Editor editor = preferences.edit();
		setDB(ADDRESS, phone, editor);
		return editor.commit();
	}

	// 获取用户的地址
	public String getAddress() {
		return preferences.getString(ADDRESS, "");
	}
	// 保存用户名字
		public boolean setName(String name) {
			SharedPreferences.Editor editor = preferences.edit();
			setDB(NAME, name, editor);
			return editor.commit();
		}

		// 获取用户的地址
		public String getName() {
			return preferences.getString(NAME, "");
		}
	// 请求数据
	public static String get(String url) {
		String result = null;
		try {
			HttpGet httpget = new HttpGet(url);
			HttpClient hc = new DefaultHttpClient();
			HttpResponse hp = hc.execute(httpget);
			if (hp.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(hp.getEntity());
				return result;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	// 得到版本号
	public  String getVersion(Context context) {
		String version = null ;
		try {
			PackageManager manager = context.getPackageManager();
			PackageInfo info = manager.getPackageInfo(context.getPackageName(),
					0);
			version = info.versionName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return version;
	}
	//提示框
	public void showDialog(Context context,String content){
		new AlertDialog.Builder(context).setTitle("提示").setMessage(content).setPositiveButton("确定",null).create().show();
	}
	// 检查是否有网络
	public static boolean checkNet(Context context) {
		boolean flag = false;
		ConnectivityManager connectManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectManager.getActiveNetworkInfo() != null)
			flag = connectManager.getActiveNetworkInfo().isAvailable();
		return flag;
	}
	public int dp2px(int dp) {
		return (int) (dp * getDisplayDensity() +0.5f);
	}
	public int px2dp(int px) {
		return (int) (px / getDisplayDensity() +0.5f);
	}
	
	public int pxToSp(int px){
		return (int)(px/dm.scaledDensity);
	}
	
	public int spToPx(int sp){
		return (int)(sp*dm.scaledDensity);
	}

	/**
	 * 获取 屏幕像素 px
	 * @return Integer[高度，宽度]
	 */
	public int[] getDisplayHightAndWightPx(){
		return new int[]{dm.heightPixels,dm.widthPixels};		
	}
	/**
	 * 获取 屏幕像素 dp
	 * @return Integer[高度，宽度]
	 */
	public int[] getDisplayHightAndWightDp(){
		return new int[]{px2dp(getDisplayHightAndWightPx()[0]),px2dp(getDisplayHightAndWightPx()[1])};
	}
	
	/**
	 *  获取像素密度
	 * @return
	 */
	public float getDisplayDensity(){
		return dm.density;
	}
	private void initImageLoader(){
		DisplayImageOptions options = new DisplayImageOptions.Builder()
        	.cacheOnDisc()
        	.cacheInMemory()
        	.resetViewBeforeLoading()
        	.bitmapConfig(Bitmap.Config.RGB_565)
        	.imageScaleType(ImageScaleType.EXACTLY)
        	.build();
		
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this.getApplicationContext())
			.threadPriority(Thread.NORM_PRIORITY - 2)
			.threadPoolSize(3)
//			.memoryCache(new WeakMemoryCache())
			.tasksProcessingOrder(QueueProcessingType.LIFO)
//			.enableLogging() // Not necessary in common
			.defaultDisplayImageOptions(options)
			.build();
		ImageLoader.getInstance().init(config);
	}
	public static String httpGet(String url) {
		String result = null;
		try {
			HttpGet httpget = new HttpGet(url);
			HttpClient hc = new DefaultHttpClient();
			HttpResponse hp = hc.execute(httpget);
			if (hp.getStatusLine().getStatusCode() == 200) {
				result = EntityUtils.toString(hp.getEntity());
				return result;
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	public int title_h(){
		return (int)(HhhApp.getInstance().getDisplayHightAndWightPx()[0] * 0.065);
	}
}
